package com.haojii.notifier.easytv;
import java.io.IOException;
import java.util.Date;
import java.util.List;
import java.util.logging.Level;
import java.util.logging.Logger;

import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import com.google.appengine.api.datastore.Key;
import com.google.appengine.api.datastore.KeyFactory;
import com.haojii.notifier.observer.EmailNotifier;
import com.haojii.notifier.user.User;
import com.haojii.notifier.user.UserUtils;

@SuppressWarnings("serial")
public class EasytvCronServlet extends HttpServlet {
	private static final Logger log = Logger.getLogger(EasytvCronServlet.class.getName());
	
	@SuppressWarnings("unchecked")
	public void doGet(HttpServletRequest req, HttpServletResponse resp) throws IOException {

		if(Boolean.parseBoolean(req.getHeader("X-AppEngine-Cron")))
		{
			log.info("Cron called at "+new Date());
		}
		else
		{
			log.info("Maunal called at "+new Date());
		}
		
		resp.setContentType("text/plain");
		
		List<EasytvEntity> list = EasytvEntityUtils.list();
		log.log(Level.FINEST, "list.size()="+list.size());
		req.setAttribute("easytvEntityList", list);
		
		for (EasytvEntity easytvEntity : list) {
			EasytvParserTaskAppEngine task = new EasytvParserTaskAppEngine(easytvEntity);
			log.info(easytvEntity.title);
			resp.getWriter().println("["+easytvEntity.title+"] before: "+easytvEntity.getItems().size());
			
			if(easytvEntity.getItems().size() != 0)
			{
				EmailNotifier en = new EmailNotifier();
				
				for (Key key : easytvEntity.getWatchingUsers()) {
					
					User u = UserUtils.get(KeyFactory.keyToString(key));
					log.info("Key:"+key);
					log.info("User:"+u);
					en.addUserToNotifierList(u);
				}
				task.addObserver(en);
			}
			else
			{
				log.info("INIT "+easytvEntity.title);
			}
			
			task.doTask();
		}
		for (EasytvEntity e : list) {
			resp.getWriter().println("["+e.title+"] after: " + e.getItems().size());
			EasytvEntityUtils.update(e);
		}
		
/*		List<EasytvParserTaskAppEngine> easytvTaskList = null;
		if ((easytvTaskList= (List<EasytvParserTaskAppEngine>)context.getAttribute("easytvTaskList"))==null)
		{
			easytvTaskList = new ArrayList<EasytvParserTaskAppEngine>(); 
			context.setAttribute("easytvTaskList", easytvTaskList);
		}
		
		for (EasytvParserTaskAppEngine task : easytvTaskList) {
			resp.getWriter().println(task.getEasytvEntity().title+" -> " + task.getEasytvEntity().items.size());
			EmailNotifier en = new EmailNotifier();
			en.addUserToNotifierList(new User("1376412XXXX", "coolnotifier@gmail.com", "Hao"));
			
			task.addObserver(en);
			task.doTask();
		}*/
		
		
		/*for (EasytvParserTaskAppEngine task : easytvTaskList) {
			resp.getWriter().println(task.getEasytvEntity().title+" -> " + task.getEasytvEntity().items.size());
		}*/
		resp.getWriter().flush();
		resp.getWriter().close();
	}

}
